/*
 * @Author: SingleBiu
 * @Date: 2025-10-28 21:57:53
 * @LastEditors: SingleBiu
 * @LastEditTime: 2025-10-29 20:03:52
 * @Description: file content
 */
package controllers

import (
	"es_user/models"

	"github.com/beego/beego/v2/server/web"
)

type UserController struct {
	web.Controller
}

func (c *UserController) Get() {
	// 初始化测试数据
	models.InitTestData()
	c.TplName = "index.html"
}

func (c *UserController) Login() {
	id := c.GetString("id")
	name := c.GetString("name")

	if id == "" || name == "" {
		c.Ctx.WriteString("ID和姓名不能为空")
		return
	}

	exists, err := models.UserExists(id, name)
	if err != nil {
		c.Ctx.WriteString("登录失败: " + err.Error())
		return
	}

	if exists {
		c.SetSession("user_id", id)
		c.SetSession("user_name", name)
		c.Redirect("/dashboard", 302)
	} else {
		// 如果用户不存在，创建新用户
		user := &models.User{
			ID:   id,
			Name: name,
		}
		err := models.AddUser(user)
		if err != nil {
			c.Ctx.WriteString("创建用户失败: " + err.Error())
			return
		}
		c.SetSession("user_id", id)
		c.SetSession("user_name", name)
		c.Redirect("/dashboard", 302)
	}
}

func (c *UserController) Dashboard() {
	userID := c.GetSession("user_id")
	userName := c.GetSession("user_name")

	if userID == nil || userName == nil {
		c.Redirect("/", 302)
		return
	}

	c.Data["UserID"] = userID
	c.Data["UserName"] = userName
	c.TplName = "dashboard.html"
}

func (c *UserController) GetAllUsers() {
	users, err := models.GetAllUsers()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"error": err.Error(),
		}
	} else {
		c.Data["json"] = map[string]interface{}{
			"users": users,
		}
	}
	c.ServeJSON()
}

func (c *UserController) Logout() {
	c.DelSession("user_id")
	c.DelSession("user_name")
	c.Redirect("/", 302)
}
